// stores/user.js
import { defineStore } from 'pinia';
import { ApiService } from '@/api/apiService'; // 假设ApiService已经正确导入

export const useUserStore = defineStore('user', {
    state: () => ({
        user: null, // 存储用户信息的对象
    }),
    actions: {
        setUser(user) {
            this.user = user;
        },
        // 用户登录
        async login(user) {
            console.log('Login action called');
            console.log('Login action called with username:', user.username, 'and password:', user.password);
            try {
                const response = await ApiService.login(user.username, user.password);
                console.log('Login response:', response);
                if (response.status === 200) {
                    this.setUser(response.data.user);
                    return true;
                } else {
                    return false;
                }
            } catch (error) {
                throw error;
            }
        },
        async register(user) {
            try {

                const response = await ApiService.register(user.username, user.password);

                if (response.status === 201) {
                    return true;
                } else {
                    return false;
                }
            } catch (error) {
                console.log('error:', error);
                throw error;
            }
        },
        logout() {
            this.setUser(null);
        }
    },
    getters: {
        getUser: (state) => state.user
    },
    persist: {
        enabled: true, // 启用持久化
        strategies: [
            {
                key: 'pinia_user', // 自定义存储的键名
                storage: localStorage, // 使用 localStorage
            },
        ],
    },
});